package com.hemaapp.yjnh.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.hm_FrameWork.view.RefreshLoadmoreLayout;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.adapter.FarmerListAdapter;
import com.hemaapp.yjnh.bean.Client;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.User;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import xtom.frame.util.XtomSharedPreferencesUtil;
import xtom.frame.util.XtomToastUtil;
import xtom.frame.view.XtomListView;
import xtom.frame.view.XtomRefreshLoadmoreLayout;
import xtom.frame.view.XtomRefreshLoadmoreLayout.OnStartListener;

/**
 * 田家列表
 * @author ZhangGuiyou
 *         Date:2015-8-14 14:49
 */
public class FarmerListActivity extends BaseActivity implements OnClickListener {

    @Bind(R.id.title_farmer)
    TextView titleFarmer;
    @Bind(R.id.tv_city)
    TextView tvCity;
    @Bind(R.id.tv_default)
    TextView tvDefault;
    @Bind(R.id.layout_default)
    LinearLayout layoutDefault;
    @Bind(R.id.layout_sales)
    LinearLayout layoutSales;
    @Bind(R.id.layout_price)
    LinearLayout layoutPrice;
    @Bind(R.id.listview)
    XtomListView listview;
    @Bind(R.id.refreshLoadmoreLayout)
    RefreshLoadmoreLayout refreshLoadmoreLayout;

    private ArrayList<Client> clients = new ArrayList<>();//推荐田家
    private FarmerListAdapter clientAdapter;
    private User user;
    private String keyid = "";
    private String orderby = "1";//1：智能排序;    2：热销;    3：好评;    4：价格;
    private String ordertype = "1";//1：降序;    2：升序
    private int page = 0;//当前加载页数

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_farmer_list);
        ButterKnife.bind(this);
        super.onCreate(savedInstanceState);
        user = getApplicationContext().getUser();
        String token = user == null ? "" : user.getToken();
        getNetWorker().clientList(token, "2", keyid, orderby, ordertype, "", page + "", "", "");
    }

    @Override
    protected void findView() {
    }

    @Override
    protected void getExras() {
        keyid = mIntent.getStringExtra("keyid");
    }

    @Override
    protected void setListener() {
        tvCity.setText(keyid);
        titleFarmer.setText(mIntent.getStringExtra("title"));
        boolean changeCity = mIntent.getBooleanExtra("change", false);
        if (changeCity)
            tvCity.setVisibility(View.VISIBLE);
        else
            tvCity.setVisibility(View.GONE);
        refreshLoadmoreLayout.setOnStartListener(new OnStartListener() {
            @Override
            public void onStartRefresh(XtomRefreshLoadmoreLayout xtomRefreshLoadmoreLayout) {
                page = 0;
                String token = user == null ? "" : user.getToken();
                getNetWorker().clientList(token, "2", keyid, orderby, ordertype, "", page + "", "", "");
            }

            @Override
            public void onStartLoadmore(XtomRefreshLoadmoreLayout xtomRefreshLoadmoreLayout) {
                page++;
                String token = user == null ? "" : user.getToken();
                getNetWorker().clientList(token, "2", keyid, orderby, ordertype, "", page + "", "", "");
            }
        });
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case CLIENT_LIST:
                showProgressDialog("请稍候");
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case CLIENT_LIST:
                cancelProgressDialog();
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case CLIENT_LIST:
                String page = netTask.getParams().get("page");
                HemaPageArrayResult<Client> cResult = (HemaPageArrayResult<Client>) baseResult;
                if (cResult == null || cResult.getObjects() == null)
                    return;
                if ("0".equals(page)) {// 刷新
                    refreshLoadmoreLayout.refreshSuccess();
                    clients.clear();
                    clients.addAll(cResult.getObjects());
                } else {
                    refreshLoadmoreLayout.loadmoreSuccess();
                    if (cResult.getObjects().size() > 0)
                        this.clients.addAll(cResult.getObjects());
                    else {
                        refreshLoadmoreLayout.setLoadmoreable(false);
                        XtomToastUtil.showShortToast(mContext, "已经到最后啦");
                    }
                }
                refreshClient(-1);
                break;
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case CLIENT_LIST:
                if (page == 0) {// 刷新
                    refreshLoadmoreLayout.refreshFailed();
                } else {
                    refreshLoadmoreLayout.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(mContext, "获取信息失败" + baseResult.getMsg());
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case CLIENT_LIST:
                if (page == 0) {// 刷新
                    refreshLoadmoreLayout.refreshFailed();
                } else {
                    refreshLoadmoreLayout.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(mContext, "获取信息失败，请稍后再试");
                refreshClient(failedType);
                break;
        }
    }

    /**
     * 刷新田家列表
     */
    private void refreshClient(int failedType) {
        if (null == clientAdapter) {
            clientAdapter = new FarmerListAdapter(mContext, clients);
            clientAdapter.setEmptyString("暂无田家");
            listview.setAdapter(clientAdapter);
        } else {
            clientAdapter.notifyDataSetChanged();
        }
        clientAdapter.setFailtype(failedType);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != -1)
            return;
        switch (requestCode) {
            case 1:// 选择城市
                keyid = getCityName();
                tvCity.setText(keyid);
                refreshLoadmoreLayout.getOnStartListener().onStartRefresh(refreshLoadmoreLayout);
                //2016.10.31 start 为了和iOS一致，这里田家、乐乐、走走、农需的地区都单独保存
                XtomSharedPreferencesUtil.save(mContext, "city_farmer", keyid);
                EventBusMsg msg = new EventBusMsg();
                msg.setType(EventBusConfig.UPDATE_FARMER_ADDRESS);
                EventBus.getDefault().post(msg);
                //2016.10.31 end 为了和iOS一致，这里田家、乐乐、走走、农需的地区都单独保存
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @OnClick({R.id.title_left_btn, R.id.title_right_img, R.id.layout_default,
            R.id.layout_sales, R.id.layout_price, R.id.tv_city})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_btn:
                finish();
                break;
            case R.id.title_right_img:
                Intent itSearch = new Intent(mContext, SearchActivity.class);
                itSearch.putExtra("assort", "田家");
                startActivity(itSearch);
                break;
            case R.id.tv_city:
                Intent it = new Intent(mContext, CityActivity.class);
                it.putExtra("type", 1);//显示所有地级市
                it.putExtra("parent_id", "-1");
                startActivityForResult(it, 1);
                break;
            case R.id.layout_default:
                if (orderby.equals("1")) {
                    if (ordertype.equals("1"))
                        ordertype = "2";
                    else {
                        ordertype = "1";
                    }
                }else {
                    layoutDefault.setBackgroundColor(Color.parseColor("#ffae40"));
                    layoutPrice.setBackgroundColor(Color.parseColor("#00464a"));
                    layoutSales.setBackgroundColor(Color.parseColor("#00464a"));
                    orderby = "1";
                }
                refreshLoadmoreLayout.getOnStartListener().onStartRefresh(refreshLoadmoreLayout);
                break;
            case R.id.layout_sales:
                if (orderby.equals("2")) {
                    if (ordertype.equals("1"))
                        ordertype = "2";
                    else {
                        ordertype = "1";
                    }
                }else {
                    layoutSales.setBackgroundColor(Color.parseColor("#ffae40"));
                    layoutPrice.setBackgroundColor(Color.parseColor("#00464a"));
                    layoutDefault.setBackgroundColor(Color.parseColor("#00464a"));
                    orderby = "2";
                }
                refreshLoadmoreLayout.getOnStartListener().onStartRefresh(refreshLoadmoreLayout);
                break;
            case R.id.layout_price://好评
                if (orderby.equals("3")) {
                    if (ordertype.equals("1"))
                        ordertype = "2";
                    else {
                        ordertype = "1";
                    }
                }else {
                    layoutPrice.setBackgroundColor(Color.parseColor("#ffae40"));
                    layoutDefault.setBackgroundColor(Color.parseColor("#00464a"));
                    layoutSales.setBackgroundColor(Color.parseColor("#00464a"));
                    orderby = "3";
                }
                refreshLoadmoreLayout.getOnStartListener().onStartRefresh(refreshLoadmoreLayout);
                break;
        }
    }
}
